//
//  BDGroupChooseViewController.m
//  BadBoy
//
//  Created by wen on 2017/6/9.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDGroupChooseViewController.h"
#import "BDGroupChooseTableViewCell.h"
#import "BDUserModel.h"
#import "PinYin4Objc.h"
#import "UIViewController+SearchController.h"
#import <JMessage/JMessage.h>

@interface BDGroupChooseViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchControllerDelegate, UISearchResultsUpdating>
{
    NSUInteger _lastContactsHash;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *fridentArray;
@property (strong, nonatomic) NSMutableArray *indexList;    // 存放右侧索引

@property (strong, nonatomic) NSMutableArray *chooseArray;
@property (strong, nonatomic) NSMutableArray *searchArray;

@end

@implementation BDGroupChooseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"选择联系人");
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 5, 25 ,25)];
    [backButton setImage:[UIImage imageNamed:@"cha"] forState:UIControlStateNormal];
    UIBarButtonItem *backBarButton=[[UIBarButtonItem alloc]initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backBarButton;
    
    [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithTitle:ASLocalizedString(@"取消")style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonAction)];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:ASLocalizedString(@"完成")style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonAction)];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    [self layoutSubviews];
    [self getLocalFriendsAction];
    self.chooseArray = [NSMutableArray array];
    
    self.hidesNavigationBarDuringPresentation = NO;
    [self enableSearchController];
    
    [self.tableView reloadData];
    
    UITableView *searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, 44)];
    searchTableView.tableHeaderView = self.searchController.searchBar;
    [self.view addSubview:searchTableView];
    
}

- (void)cancelButtonAction{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)doneButtonAction{
    NSMutableArray *groupArray = [NSMutableArray array];
    
    if (self.chooseType == BDChatChooseTypeCreat) {
        for (NSNumber *number in self.startArray) {
            [groupArray addObject:[NSString stringWithFormat:@"%@", number]];
        }
    }
    for (NSNumber *number in self.chooseArray) {
        [groupArray addObject:[NSString stringWithFormat:@"%@", number]];
    }
    
//    NSMutableArray *nameArray = [NSMutableArray array];
//    for (NSArray *litArray in self.fridentArray) {
//        for (BDFridentInfo *firend in litArray) {
//            if ([groupArray containsObject:[NSString stringWithFormat:@"%@", firend.user_id]]) {
//                BDUserModel *user = [BDUserModel creatWithFriendInfo:firend];
//                [nameArray addObject:user.nickname];
//            }
//        }
//    }
//    
//    if (self.chooseType == BDChatChooseTypeCreat) {
//        EMError *error = nil;
//        EMGroupOptions *setting = [[EMGroupOptions alloc] init];
//        setting.maxUsersCount = 500;
//        setting.style = EMGroupStylePrivateMemberCanInvite;// 创建不同类型的群组，这里需要才传入不同的类型
//        
//        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
//        BDUserModel *currentUser = [BDUserModel getCurrentUser];
//        NSString *qun = [NSString stringWithFormat:ASLocalizedString(@"%@创建的群"), currentUser.nickname];
//        [[EMClient sharedClient].groupManager createGroupWithSubject:qun description:@"" invitees:groupArray message:ASLocalizedString(@"邀请您加入群组")setting:setting completion:^(EMGroup *aGroup, EMError *aError) {
//            [MBManager hideAlert];
//            if(!error){
//                
//                //本地保存群组信息，包括创建人在内所有信息
//                BDChatGroupModel *group = [[BDChatGroupModel alloc] init];
//                group.groupid = aGroup.groupId;
//                group.groupname = qun;
//                group.owner_id = [NSString stringWithFormat:@"%@", @(currentUser.user_id)];
//                [group.memberList addObject:currentUser];
//                group.isBlocked = NO;
//                group.groupNotes = aGroup.description;
//                
//                NSString *groupPath = [DocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"group_%@.plist", group.groupid]];
//                if ([group.mj_keyValues writeToFile:groupPath atomically:YES]) {
//                    NSMutableArray *groupReferenceArray = [NSMutableArray arrayWithContentsOfFile:GroupRefrencePath];
//                    [groupReferenceArray addObject:group.groupid];
//                    if ([groupReferenceArray writeToFile:GroupRefrencePath atomically:YES]) {
//                        //这里由于会有回调来处理，所以这里不需要再发送透传消息
//                        //本地插入空消息用来显示提示信息
//                        NSString *from = [[EMClient sharedClient] currentUsername];
//                        long long timeInterval = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970] * 1000;
//                        EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:group.groupid type:EMConversationTypeGroupChat createIfNotExist:YES];
//                        //这里插入消息
//                        NSString *text = @"";
//                        EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
//                        NSString *extStr = [nameArray componentsJoinedByString:@"、"];
//                        extStr = [NSString stringWithFormat:@"%@%@%@", ASLocalizedString(@"已对"), extStr,ASLocalizedString(@"发送邀请")];
//                        EMMessage *locationMessage = [[EMMessage alloc] initWithConversationID:conversation.conversationId from:from to:conversation.conversationId body:body ext:@{@"messageSpecialType":@"timeString",@"detailInfo":extStr}];
//                        locationMessage.chatType = EMConversationTypeGroupChat;
//                        locationMessage.timestamp = timeInterval;
//                        [conversation insertMessage:locationMessage error:nil];
//                        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshLocationChatMessage" object:locationMessage];
//                        [self dismissViewControllerAnimated:NO completion:nil];
//                        //然后跳转到群聊天界面
//                        [[NSNotificationCenter defaultCenter] postNotificationName:@"jumpToNewGroupChat" object:group];
//                    }
//                }
//                
//            }else{
//                [MBManager showBriefAlert:ASLocalizedString(@"创建失败")clickHidden:NO clickBlock:nil];
//            }
//        }];
//    }else {
//        [[EMClient sharedClient].groupManager addMembers:groupArray toGroup:self.groupID message:ASLocalizedString(@"邀请您加入群组")completion:^(EMGroup *aGroup, EMError *aError) {
//            if (!aError) {
//                [MBManager showBriefAlert:ASLocalizedString(@"已成功发送邀请")clickHidden:YES clickBlock:nil];
//                NSString *from = [[EMClient sharedClient] currentUsername];
//                long long timeInterval = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970] * 1000;
//                EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.groupID type:EMConversationTypeGroupChat createIfNotExist:YES];
//                //这里插入消息
//                NSString *text = @"";
//                EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
//                NSString *extStr = [nameArray componentsJoinedByString:@"、"];
//                extStr = [NSString stringWithFormat:@"%@%@%@", ASLocalizedString(@"已对"), extStr,ASLocalizedString(@"发送邀请")];
//                EMMessage *locationMessage = [[EMMessage alloc] initWithConversationID:conversation.conversationId from:from to:conversation.conversationId body:body ext:@{@"messageSpecialType":@"timeString",@"detailInfo":extStr}];
//                locationMessage.chatType = EMConversationTypeGroupChat;
//                locationMessage.timestamp = timeInterval;
//                [conversation insertMessage:locationMessage error:nil];
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshLocationChatMessage" object:locationMessage];
//                [self dismissViewControllerAnimated:YES completion:nil];
//            }else{
//                [MBManager showBriefAlert:ASLocalizedString(@"发送邀请失败")clickHidden:YES clickBlock:nil];
//            }
//        }];
//    }
}

- (void)layoutSubviews{
    [self.view addSubview:self.tableView];
}

#pragma mark 加载本地好友数据
-(void)getLocalFriendsAction{
    [JMSGFriendManager getFriendList:^(id resultObject, NSError *error) {
        if (error) {
            
        }else{
            NSMutableArray *friendArray = resultObject;
            
            for (int i = 0; i < friendArray.count; i++) {
                JMSGUser *firend = friendArray[i];
                NSString *userId = [firend.username stringByReplacingOccurrencesOfString:@"beboy_" withString:@""];
                if ([userId integerValue] <= 100) {
                    [friendArray removeObject:firend];
                    i--;
                }
            }
            
            if (friendArray.hash == _lastContactsHash) {
                return;
            }
            _lastContactsHash = self.fridentArray.hash;
            NSArray *resultArray = [self arrayForSections:friendArray];
            
            self.fridentArray = [NSMutableArray array];
            for (int i = 0; i < resultArray.count; i++) {
                NSMutableArray *liArr = [NSMutableArray arrayWithArray:resultArray[i]];
                [self.fridentArray addObject:liArr];
            }
        }
    }];
}

- (NSMutableArray *)arrayForSections:(NSArray *)objects {
    
    // sectionTitlesCount 27 , A - Z + #
    //根据nickname
    SEL selector = @selector(nickname);
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    // section number
    NSInteger sectionTitlesCount = [[collation sectionTitles] count];
    
    // Create 27 sections' data
    NSMutableArray *mutableSections = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    for (NSUInteger idx = 0; idx < sectionTitlesCount; idx++) {
        [mutableSections addObject:[NSMutableArray array]];
    }
    
    // Insert records
    for (id object in objects) {
        NSInteger sectionNumber = [collation sectionForObject:object collationStringSelector:selector];
        [[mutableSections objectAtIndex:sectionNumber] addObject:object];
    }
    
    // sort in section
    for (NSUInteger idx = 0; idx < sectionTitlesCount; idx++) {
        NSArray *objectsForSection = [mutableSections objectAtIndex:idx];
        [mutableSections replaceObjectAtIndex:idx withObject:[[UILocalizedIndexedCollation currentCollation] sortedArrayFromArray:objectsForSection collationStringSelector:selector]];
    }
    
    // Remove empty sections && insert table data
    NSMutableArray *existTitleSections = [NSMutableArray array];
    for (NSMutableArray *section in mutableSections) {
        if ([section count] > 0) {
            [existTitleSections addObject:section];
        }
    }
    
    // Remove empty sections Index in indexList
    NSMutableArray *existTitles = [NSMutableArray array];
    NSArray *allSections = [collation sectionIndexTitles];
    
    for (NSUInteger i = 0; i < [allSections count]; i++) {
        if ([mutableSections[ i ] count] > 0) {
            [existTitles addObject:allSections[ i ]];
        }
    }
    
    //create indexlist data array
    self.indexList = [NSMutableArray arrayWithArray:existTitles];
    
    return existTitleSections;
}

#pragma mark  --------------------------searchBarDelegate--------------------------------

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *key = searchController.searchBar.text;
    NSMutableArray *datasource = [NSMutableArray array];
    for (NSArray *litArray in self.fridentArray) {
        for (JMSGUser *friend in litArray) {
            if ([friend.nickname containsString:key]) {
                [datasource addObject:friend];
            }
        }
    }
    
    self.searchArray = datasource;
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchController.active) {
        return 1;
    }
    return self.fridentArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return self.searchArray.count;
    }
    return [self.fridentArray[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.searchController.active) {
        return 0;
    }
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc] init];
    UILabel *label = [[UILabel alloc] init];
    label.text = self.indexList[section];
    label.font = [UIFont boldSystemFontOfSize:14];
    label.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
    
    [label sizeToFit];
    label.left = 10;
    label.centerY = 10;
    [headView addSubview:label];
    
    return headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDGroupChooseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chooseCell" forIndexPath:indexPath];
    JMSGUser *friend = nil;
    
    if (self.searchController.active) {
        friend = self.searchArray[indexPath.row];
    }else{
        friend = self.fridentArray[indexPath.section][indexPath.row];
    }
    
    BDGroupChooseState chooseState = BDGroupChooseStateNormal;
    if ([self.startArray containsObject:friend.nickname]) {
        chooseState = BDGroupChooseStateAlready;
    }else if ([self.chooseArray containsObject:friend.nickname]) {
        chooseState = BDGroupChooseStateNewAdd;
    }
    [cell configeWithModel:friend chooseState:chooseState];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    JMSGUser *friend = nil;
    if (self.searchController.active) {
        friend = self.searchArray[indexPath.row];
    }else{
        friend = self.fridentArray[indexPath.section][indexPath.row];
    }
    if ([self.startArray containsObject:friend.nickname]) {
        return;
    }
    if ([self.chooseArray containsObject:friend.nickname]) {
        [self.chooseArray removeObject:friend.nickname];
        if (self.chooseArray.count == 0) {
            self.navigationItem.rightBarButtonItem.enabled = NO;
        }
    }else{
        [self.chooseArray addObject:friend.nickname];
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }
    [self.tableView reloadData];
}

//添加tableview 右侧索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (self.searchController.active) {
        return nil;
    }
    return _indexList;
}

- (void)searchTextChangeWithString:(NSString *)aString{
    [self.searchArray removeAllObjects];
    for (BDUserModel *user in self.fridentArray) {
        if ([user.nickname containsString:aString]) {
            [self.searchArray addObject:user];
        }
    }
    [self.tableView reloadData];
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 108, kBDScreenWidth, kBDScreenHeight - 108) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[BDGroupChooseTableViewCell class] forCellReuseIdentifier:@"chooseCell"];
        _tableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorInset = UIEdgeInsetsZero;
    }
    return _tableView;
}

- (NSMutableArray *)searchArray{
    if (!_searchArray) {
        self.searchArray = [NSMutableArray array];
    }
    return _searchArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
